import { Injectable } from '@nestjs/common'
import { InjectRepository } from '@nestjs/typeorm'
import { CacheEnum, DelFlagEnum } from 'src/common/enum'
import { ResultData } from 'src/common/utils/result'
import { RedisService } from 'src/modules/redis/redis.service'
import { In, Repository } from 'typeorm'
import {
  CreateDictDataDto,
  CreateDictTypeDto,
  ListDictData,
  ListDictType,
  UpdateDictDataDto,
  UpdateDictTypeDto
} from './dto'
import { SysDictDataEntity } from './entities/dict.data.entity'
import { SysDictTypeEntity } from './entities/dict.type.entity'

@Injectable()
export class DictService {
  constructor(
    @InjectRepository(SysDictDataEntity)
    private readonly sysDictDataEntityRep: Repository<SysDictDataEntity>,
    @InjectRepository(SysDictTypeEntity)
    private readonly sysDictTypeEntityRep: Repository<SysDictTypeEntity>,
    private readonly redisService: RedisService
  ) {}

  async findAllType(query: ListDictType) {
    const entity = this.sysDictTypeEntityRep.createQueryBuilder('entity')
    entity.where('entity.delFlag = :delFlag', { delFlag: DelFlagEnum.NORMAL })
    if (query.dictName) {
      entity.andWhere(`entity.dictName LIKE "%${query.dictName}%"`)
    }
    if (query.dictType) {
      entity.andWhere(`entity.dictType LIKE "%${query.dictType}%"`)
    }
    if (query.status) {
      entity.andWhere(`entity.status = :status`, { status: query.status })
    }
    if (query.params?.beginTime && query.params?.endTime) {
      entity.andWhere('entity.createTime BETWEEN :start AND :end', {
        start: query.params.beginTime,
        end: query.params.endTime
      })
    }
    entity.skip(query.pageSize * (query.pageNum - 1)).take(query.pageSize)
    const [list, total] = await entity.getManyAndCount()

    return ResultData.ok({
      list,
      total
    })
  }

  /**
   * 根据字典类型查询一个数据类型的信息。
   *
   * @param dictType 字典类型字符串。
   * @returns 返回查询到的数据类型信息，如果未查询到则返回空。
   */
  async findOneDataType(dictType: string) {
    // 尝试从Redis缓存中获取字典数据
    let data = await this.redisService.get(`${CacheEnum.SYS_DICT_KEY}${dictType}`)
    if (data) {
      return ResultData.ok(data)
    }
    // 从数据库中查询数据字典
    data = await this.sysDictDataEntityRep.find({
      where: {
        dictType: dictType,
        delFlag: DelFlagEnum.NORMAL
      }
    })
    // 将查询到的数据存入 Redis 缓存，并返回数据
    await this.redisService.set(`${CacheEnum.SYS_DICT_KEY}${dictType}`, data)
    return ResultData.ok(data)
  }

  async findOneType(dictId: number) {
    const data = await this.sysDictTypeEntityRep.findOne({
      where: {
        dictId: dictId,
        delFlag: DelFlagEnum.NORMAL
      },
      select: ['dictName', 'dictType', 'dictId', 'status', 'remark']
    })
    return ResultData.ok(data)
  }

  /**
   * @description 创建字典类型数据
   */
  async createType(createDictTypeDto: CreateDictTypeDto) {
    await this.sysDictTypeEntityRep.save(createDictTypeDto)
    return ResultData.ok({})
  }

  /**
   * @description 更新字典类型数据
   */
  async updateType(updateDictTypeDto: UpdateDictTypeDto) {
    await this.sysDictTypeEntityRep.update({ dictId: updateDictTypeDto.dictId }, updateDictTypeDto)
    return ResultData.ok({})
  }

  /**
   * @description 删除字典类型
   */
  async deleteType(dictIds: number[]) {
    await this.sysDictTypeEntityRep.update({ dictId: In(dictIds) }, { delFlag: DelFlagEnum.DELETE })
    return ResultData.ok({})
  }
  /**
   * @description 获取所有的字段类型-下拉数据
   */
  async findOptionselect() {
    const data = await this.sysDictTypeEntityRep.find({
      where: {
        delFlag: DelFlagEnum.NORMAL
      }
    })
    return ResultData.ok(data)
  }
  /**
   * @description 获取字典类型下的所有数据
   */
  async findAllData(query: ListDictData) {
    const entity = this.sysDictDataEntityRep.createQueryBuilder('entity')
    entity.where('entity.delFlag = :delFlag', { delFlag: DelFlagEnum.NORMAL })
    if (query.dictLabel) {
      entity.andWhere(`entity.dictLabel LIKE "%${query.dictLabel}%"`)
    }
    if (query.dictType) {
      entity.andWhere(`entity.dictType LIKE "%${query.dictType}%"`)
    }
    if (query.status) {
      entity.andWhere('entity.status = :status', { status: query.status })
    }
    // 分页计算
    entity.skip(query.pageSize * (query.pageNum - 1)).take(query.pageSize)
    const [list, total] = await entity.getManyAndCount()
    return ResultData.ok({
      list,
      total
    })
  }
  // 创建字典数据
  async createDictData(createDictDataDto: CreateDictDataDto) {
    await this.sysDictDataEntityRep.save(createDictDataDto)
    return ResultData.ok({})
  }
  // 查找一条字典数据
  async findOneDictData(dictCode: number) {
    const data = await this.sysDictDataEntityRep.findOne({
      where: {
        dictCode: dictCode,
        delFlag: DelFlagEnum.NORMAL
      }
    })
    return ResultData.ok(data)
  }

  // 更新字典数据
  async updateDictData(updateDictDataDto: UpdateDictDataDto) {
    await this.sysDictDataEntityRep.update(
      {
        dictCode: updateDictDataDto.dictCode
      },
      updateDictDataDto
    )
    return ResultData.ok({})
  }
  // 删除字典数据
  async deleteDictData(dictId: number) {
    await this.sysDictDataEntityRep.update(
      {
        dictCode: dictId
      },
      {
        delFlag: DelFlagEnum.DELETE
      }
    )
    return ResultData.ok({})
  }
}
